package com.teamgame.teamgame;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Common {

    DataBaseHelper myDbHelper;

    public Common(Context context) {
        myDbHelper = new DataBaseHelper(context);

        try {
            myDbHelper.createDataBase(true);
        } catch (IOException ioe) {
            Log.d("TeamGame", "Unable create database");
        }

        try {
            myDbHelper.openDataBase();
        } catch (SQLException sqle) {
            Log.d("TeamGame", "Unable connect database");
        }
    }

    public void closeDbHelper() {
        myDbHelper.close();
    }

    public List<Dictionary> findDictionary() {
        SQLiteDatabase db = myDbHelper.GetWritableDatabase();

        String query = "Select * FROM Dictionary ORDER BY Id";

        Cursor cursor = db.rawQuery(query, null);

        List<Dictionary> dictionaries = new ArrayList<Dictionary>();

        cursor.moveToFirst();
        int i = 1;
        while (!cursor.isAfterLast()) {
            Dictionary dictionary = new Dictionary();
            dictionary.setIndex(i++);
            dictionary.setId(Integer.parseInt(cursor.getString(0)));
            dictionary.setWord(cursor.getString(1));
            dictionary.setMeaning(cursor.getString(2));
            dictionaries.add(dictionary);
            cursor.moveToNext();
        }

        cursor.close();

        db.close();
        return dictionaries;
    }

    public Dictionary findDictionary(int id) {
        SQLiteDatabase db = myDbHelper.GetWritableDatabase();

        String query = "Select * FROM Dictionary WHERE Id = " + id;

        Cursor cursor = db.rawQuery(query, null);

        cursor.moveToFirst();
        Dictionary dictionary = new Dictionary();
        dictionary.setId(Integer.parseInt(cursor.getString(0)));
        dictionary.setWord(cursor.getString(1));
        dictionary.setMeaning(cursor.getString(2));

        cursor.close();

        db.close();
        return dictionary;
    }

    public int countDictionary() {
        SQLiteDatabase db = myDbHelper.GetWritableDatabase();

        String query = "Select Count(*) FROM Dictionary";

        Cursor cursor = db.rawQuery(query, null);

        cursor.moveToFirst();
        int count = cursor.getInt(0);

        cursor.close();

        db.close();
        return count;
    }
}
